<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <el-form ref="formRef" v-loading="formLoading" :model="formData" :rules="formRules" label-width="100px">
      <el-row>
        <el-col :span="24">
          <el-form-item label="学校图片" prop="picture">
            <upload-img v-model="formData.picture"/>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="学校名称" prop="name">
            <el-input v-model="formData.name" placeholder="请输入学校名称" clearable/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="学校套餐" prop="packageId">
            <el-select v-model="formData.packageId" clearable placeholder="请选择租户套餐">
              <el-option v-for="item in packageList" :label="item.name" :value="item.id"/>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="24">
          <el-form-item label="负责人" prop="leaderIds">
            <el-select v-model="formData.leaderIds" multiple placeholder="请选择" style="width: 100%" clearable>
              <el-option v-for="item in userList" :key="item.id" :label="item.nickname" :value="item.id"/>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="联系人" prop="contactName">
            <el-input v-model="formData.contactName" placeholder="请输入联系人" clearable/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系手机" prop="contactMobile">
            <el-input v-model="formData.contactMobile" placeholder="请输入联系手机" clearable/>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="所属省份" prop="province">
            <el-select v-model="formData.province" placeholder="请选择省份" filterable default-first-option>
              <el-option v-for="item in regionData" :label="item.label" :value="item.label"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <!--                    <el-form-item label="经纬度" prop="location">-->
          <!--                        <Map v-model:location="formData.location"/>-->
          <!--                    </el-form-item>-->

          <!-- 经度、纬度和按钮布局 -->
          <el-form-item label="位置" required>
            <el-row :gutter="10" style="align-items: center;">
              <el-col :span="8">
                <el-form-item prop="lng">
                  <el-input v-model="formData.lng" placeholder="请输入经度"/>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item prop="lat">
                  <el-input v-model="formData.lat" placeholder="请输入纬度"/>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-button type="primary" @click="openMap">打开地图</el-button>
              </el-col>
            </el-row>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="24">
          <el-form-item label="地址" prop="address">
            <el-input v-model="formData.address" clearable/>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="管理员账号" prop="username">
            <el-input v-model="formData.username" placeholder="请输入用户名" clearable :disabled="formData.id"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item v-if="formData.id" label="管理员昵称" prop="nickname">
            <el-input v-model="formData.nickname" disabled/>
          </el-form-item>
          <el-form-item v-else label="管理员密码" prop="password">
            <el-input v-model="formData.password" placeholder="请输入用户密码" show-password type="password" clearable/>
            <el-text type="info">默认密码: yxt123</el-text>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="账号额度" prop="accountCount">
            <el-input-number v-model="formData.accountCount" :min="0" controls-position="right" placeholder="请输入额度"
                             clearable/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="过期时间" prop="expireTime">
            <el-date-picker v-model="formData.expireTime" unlink-panels placeholder="请选择过期时间" type="date"
                            value-format="x" clearable/>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="formData.status">
              <el-radio v-for="dict in getIntDictOptions(DICT_TYPE.COMMON_STATUS)" :label="dict.value">
                {{ dict.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="人脸识别" prop="isFace">
            <el-radio-group v-model="formData.isFace">
              <el-radio v-for="dict in getIntDictOptions(DICT_TYPE.COMMON_STATUS)" :label="dict.value">
                {{ dict.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="formData.remark" placeholder="请输入内容" type="textarea" :rows="3"/>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
import {CommonStatusEnum} from '@/utils/constants'
import {useSchoolApi} from "@/api/yxt/school";
import * as UserApi from '@/api/system/user'
import {DICT_TYPE, getIntDictOptions} from "@/utils/dict";
import {useMessage} from "@/components/Notice";
import * as TenantPackageApi from "@/api/system/tenantPackage";
import {regionData} from "element-china-area-data";

defineOptions({name: 'YxtSchoolForm'})

const {t} = useI18n()
const schoolApi = useSchoolApi();

const dialogVisible = ref(false)
const dialogTitle = ref('')
const formLoading = ref(false)
const formType = ref('')
const formData = ref({
  id: undefined,
  picture: '',
  name: '',
  packageId: undefined,
  leaderIds: [],
  contactName: undefined,
  contactMobile: undefined,
  province: '',
  lng: '',
  lat: '',
  location: [],
  address: '',
  username: '',
  nickname: '',
  password: 'yxt123',
  accountCount: 1000,
  expireTime: undefined,
  domain: undefined,
  remark: '',
  status: CommonStatusEnum.ENABLE,
  isFace: CommonStatusEnum.DISABLE,
})
const formRules = reactive({
  name: [{required: true, message: '学校名称不能为空', trigger: ['blur', 'change']}],
  packageId: [{required: true, message: '租户套餐不能为空', trigger: ['blur', 'change']}],
  leaderIds: [{required: true, message: '负责人不能为空', trigger: ['blur', 'change']}],
  contactName: [{required: true, message: '联系人不能为空', trigger: 'blur'}],
  province: [{required: true, message: '省份不能为空', trigger: ['blur', 'change']}],
  // location: [{required: true, message: '经纬度参数不能为空', trigger: ['blur', 'change']}],
  username: [{required: true, message: '用户名不能为空', trigger: ['blur', 'change']},
    {min: 4, max: 16, message: "管理员账号长度为 4-16 位", trigger: 'blur'}],
  password: [{required: true, message: '用户密码不能为空', trigger: ['blur', 'change']},
    {min: 4, max: 16, message: '管理员密码长度为 4-16 位', trigger: 'blur'}],
  accountCount: [{required: true, message: '账号额度不能为空', trigger: ['blur', 'change']}],
  expireTime: [{required: true, message: '过期时间不能为空', trigger: ['blur', 'change']}],
  lng: [{required: true, message: '位置经度不能为空', trigger: ['blur', 'change']}],
  lat: [{required: true, message: '位置纬度不能为空', trigger: ['blur', 'change']}]
})
const formRef = ref()
const packageList = ref<Array<any>>([])
const userList = ref<UserApi.UserVO[]>([])

const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  if (id) {
    formLoading.value = true
    try {
      formData.value = await schoolApi.getSchool(id)
      formData.value.lng = formData.value.location[0];
      formData.value.lat = formData.value.location[1];
    } finally {
      formLoading.value = false
    }
  }
  packageList.value = await TenantPackageApi.getTenantPackageList();
  formData.value.packageId = packageList.value.at(0).id;
  userList.value = await UserApi.getSimpleUserList();
}
defineExpose({open})

const emit = defineEmits(['success'])
const submitForm = () => {
  formRef.value?.validate(async (valid: any) => {
    if (valid) {
      const data = formData.value
      try {
        // 将经纬度存储到 location 数组中
        formData.value.location = [formData.value.lng, formData.value.lat];
        if (formType.value === 'create') {
          await schoolApi.createSchool(data);
          useMessage(t('common.createSuccess'));
        } else {
          await schoolApi.updateSchool(data);
          useMessage(t('common.updateSuccess'));
        }
        dialogVisible.value = false
        emit('success')
      } finally {
        formLoading.value = false
      }
    }
  });
}

const resetForm = () => {
  formData.value = {
    id: undefined,
    picture: '',
    name: '',
    packageId: undefined,
    leaderIds: [],
    contactName: undefined,
    contactMobile: undefined,
    province: '',
    location: [],
    address: '',
    username: '',
    nickname: '',
    password: 'yxt123',
    accountCount: 1000,
    expireTime: undefined,
    domain: undefined,
    remark: '',
    status: CommonStatusEnum.ENABLE,
    isFace: CommonStatusEnum.DISABLE,
  }
  formRef.value?.resetFields()
}

// 地图打开函数
const openMap = () => {
  window.open("https://lbs.amap.com/tools/picker/", "_blank");
};
</script>
